package com.example.wotu;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link FragBookFind.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link FragBookFind#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragBookFind extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    private View view;
    private SQLiteDatabase sql;
    private TextView booklook;
    private TextView bookzhj;
    private TextView bookna;
    private TextView bookML;
    private TextView ML;
    private TextView ZJ;
    private ScrollView lookbs;
    private int bookids,bookfwl = 0,wbookids = 0,ebookids = 0;
    private String bookname;
    private int lastY,lastX;
    private LinearLayout LA;
    private RelativeLayout LB;
    private ListView ml;
    private ArrayAdapter mAdapter;
    private ArrayList<Integer> bookDataID;
    private ArrayList<String> bookData;
    private int isn = 0,is = 2,or_N,or_S,SY_JL,XLH,or_E;
    private float sy = 0,lgg = 0,cef = 0;

    //以序列为主：存储高度/id
    private TreeMap<Integer,Integer> Txlmap,Tidmap;

    public FragBookFind() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment FragBookFind.
     */
    // TODO: Rename and change types and number of parameters
    public static FragBookFind newInstance(String param1, String param2) {
        FragBookFind fragment = new FragBookFind();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        // ****104****
        view = inflater.inflate(R.layout.frag_book_find, container, false);
        mListener.onNOT_WK(104);
        bookids = getArguments().getInt("bookid");
        wbookids = bookids;
        ebookids = bookids;
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        /* 1.当链接失效时，如没有下载到的章节将不显示。*/
        getFindV();
        getBookData();
        getbook();
        getSETOnClick();
    }

    //1.获取组件；2.隐藏
    private void getFindV(){
        bookna = (TextView)view.findViewById(R.id.bookna);
        bookzhj = (TextView)view.findViewById(R.id.bookzhj);
        bookML = (TextView)view.findViewById(R.id.bookML);
        ML = (TextView)view.findViewById(R.id.ML);
        ZJ = (TextView)view.findViewById(R.id.ZJ);
        lookbs = view.findViewById(R.id.lookBS);
        booklook = view.findViewById(R.id.booklook);
        LA = view.findViewById(R.id.LA);
        LB = view.findViewById(R.id.LB);
        ml = view.findViewById(R.id.ml);
        Txlmap = new TreeMap<>();
        Tidmap = new TreeMap<>();
    }
    private void setGones(){
        LA.setVisibility(View.GONE);
        LB.setVisibility(View.GONE);
    }
    //3/4.目录
    private void getBookData(){
        getbooks();
        mAdapter = new ArrayAdapter(getActivity(),R.layout.support_simple_spinner_dropdown_item,bookData);
        ml.setAdapter(mAdapter);
    }
    private void getbooks(){
        bookDataID = new ArrayList<>();
        bookData = new ArrayList<>();
        try{
            sql = new MySQLOpen(getActivity()).getReadableDatabase();
            Cursor c = sql.rawQuery("select novelname from novel where novelid = ?",new String[]{String.valueOf(bookids)});
            while (c.moveToNext()){
                ML.setText(String.valueOf(c.getString(0)));
                break;
            }
            int isn = 0;
            Cursor cs = sql.rawQuery("select chapterid,chapxl,chapname from chapter where novelid = ? order by chapxl asc",new String[]{String.valueOf(bookids)});
            while (cs.moveToNext()){
                bookDataID.add(cs.getInt(0));
                bookData.add("["+cs.getString(1)+"] "+cs.getString(2));
                isn++;
            }
            ZJ.setText(String.valueOf(isn));
            //目录章数
            bookzhj.setText(0+" / "+isn);
            cs.close();
            sql.close();
        }catch (Exception e){
            e.printStackTrace();
            sql.close();
        }
    }
    //5.显示内容，阅读记录（网络链接还没做）
    private void getbook(){
        bookna.setText("");
        booklook.setText("");
        sql = new MySQLOpen(getActivity()).getReadableDatabase();
        try{
            //检查是否存在记录，否则第一条
            Cursor cs = sql.rawQuery("select * from recod where novelid = ?",new String[]{String.valueOf(bookids)});
            if(cs.moveToFirst()){
                do{
                    SY_JL = Integer.parseInt(cs.getString(3));
                    Log.d("huadjl","jl-1: "+SY_JL);
                    Cursor s = sql.rawQuery("select fwl from novel where novelid = ?",new String[]{String.valueOf(bookids)});
                    while (s.moveToNext()){
                        bookfwl = Integer.parseInt(s.getString(0));
                        break;
                    }
                    Cursor c = sql.rawQuery("select chapname,content,chapxl from chapter where chapterid = ?",new String[]{String.valueOf(cs.getInt(2))});
                    or_N = cs.getInt(2);
                    wbookids = ebookids = or_N;
                    while (c.moveToNext()){
                        bookna.setText(c.getString(0));
                        booklook.setText(c.getString(0)+"\n"+c.getString(1));
                        XLH = c.getInt(2);
                        //获取阅读记录，定位位置
                        lookbs.post(new Runnable() {
                            @Override
                            public void run() {
                                //初始化：刚进入
                                or_S = lookbs.getChildAt(0).getMeasuredHeight();
                                Txlmap.put(XLH,or_S);
                                Tidmap.put(XLH,or_N);
                                //就算滑动值再一章末尾，也没有问题
                                lookbs.scrollTo(0,SY_JL);
                                Log.d("huadjl","jl-2: "+SY_JL);
                            }
                        });
                        break;
                    }
                    break;
                }while (cs.moveToNext());
            }else{
                Cursor c = sql.rawQuery("select chapname,content,chapxl,chapterid from chapter where novelid = ? order by chapxl asc",new String[]{String.valueOf(bookids)});
                if(c.moveToFirst()){
                    do{
                        bookna.setText(String.valueOf(c.getString(0)));
                        booklook.setText(c.getString(0)+"\n"+c.getString(1));
                        or_N = c.getInt(3);
                        XLH = c.getInt(2);
                        lookbs.post(new Runnable() {
                            @Override
                            public void run() {
                                //有高度数据
                                or_S = lookbs.getChildAt(0).getMeasuredHeight();
                                Txlmap.put(XLH,or_S);
                                Tidmap.put(XLH,or_N);
                                getNameANDid(0,or_N,0);
                            }
                        });
                        break;
                    }while (c.moveToNext());
                }else Toast.makeText(getActivity(),"此本书并没有章节！",Toast.LENGTH_SHORT).show();
            }
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(getActivity(),"显示错误！",Toast.LENGTH_SHORT).show();
        }finally {
            sql.close();
        }
    }
    //6.点击各方面操作
    private void getSETOnClick(){
        lookbs.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                int y = (int) event.getY();
                int x = (int) event.getX();
                switch(event.getAction()){
                    case MotionEvent.ACTION_MOVE:{
                        //滑动时 lookbs.getScrollY() 被持续监听
                        sy = lookbs.getScrollY();
                        lgg = lookbs.getChildAt(0).getMeasuredHeight();
                        /*应该要第一次第一时间记录这章是否达到指定高度
                         *1.lookbs.getChildAt(0).getMeasuredHeight(); 获取在Scroll的内容总高度，如一章10735
                         *2.lookbs.getScrollY();  获取以顶部为标准的滑动距离，顶部为0
                         *3.lookbs.getHeight();  获取Scroll的显示内容高度，如1835
                         */
//                        Log.d("SJ","sj:"+sy);
                        break;
                    }
                    case MotionEvent.ACTION_DOWN:{
                        // 记录触摸点坐标
                        lastY = y;
                        lastX = x;
                        break;
                    }
                    case MotionEvent.ACTION_UP:{
                        //最终滑动停止点
                        cef = sy;
//                        for(Map.Entry<Integer,Integer> aaa : Tmap.entrySet()){
//                            Log.d("AAAA","TA:"+aaa.getKey()+","+aaa.getValue());
//                        }
//                        Log.d("SSSS","R:"+cef);

                        //如果它不足一页，无法充满整个屏幕，是无法保存阅读记录
                        //已解决到达顶部或底部刷新问题。
                        if(Math.abs(y - lastY) > 300){
                            if(y > lastY && sy == 0){
                                //上
                                getSQLSX(0);
                            }else if(y < lastY && lgg <= sy + lookbs.getHeight()){
                                //下
                                getSQLSX(1);
                            }else getNameANDid(1,0,cef);
                        }else if(Math.abs(y - lastY) < 10){
                            if(bookML.getVisibility() == View.GONE){
                                bookML.setVisibility(View.VISIBLE);
                            }else bookML.setVisibility(View.GONE);
                        }
                        break;
                    }
                }
                return false;
            }
        });
        bookML.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //目录：他只能在进来的第一次查询，还要保持与看的章节同显。
                setGones();
                LA.setVisibility(View.VISIBLE);
//                getBookData();
                mListener.onNOT_WK(107);
            }
        });
        ml.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //因点击目录章节，需重新存储数据
                Txlmap = new TreeMap<>();
                Tidmap = new TreeMap<>();
                //点击目录相当于重新刷新了
                sql = new MySQLOpen(getActivity()).getReadableDatabase();
                try{
                    Cursor cs = sql.rawQuery("select chapname,content,chapxl from chapter where chapterid = ?",new String[]{String.valueOf(bookDataID.get(i))});
                    wbookids = bookDataID.get(i);
                    ebookids = bookDataID.get(i);
                    while (cs.moveToNext()){
                        bookna.setText(String.valueOf(cs.getString(0)));
                        booklook.setText(cs.getString(0)+"\n"+cs.getString(1));
                        if(is == 1) or_S = lookbs.getChildAt(0).getMeasuredHeight() - or_E;
                        else if(is == 2) or_S = lookbs.getChildAt(0).getMeasuredHeight();
                        else or_S = 10;
                        is = 2;
                        Txlmap.put(cs.getInt(2),or_S);
                        Tidmap.put(cs.getInt(2),bookDataID.get(i));
                        getNameANDid(0,bookDataID.get(i),0);
                        isn = 0;
                        break;
                    }
                    setGones();
                    LB.setVisibility(View.VISIBLE);
                    lookbs.fullScroll(View.FOCUS_UP);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    sql.close();
                }
            }
        });
    }
    private void getSQLSX(int sx){
        sql = new MySQLOpen(getActivity()).getReadableDatabase();
        try{
            int SorX = 0;
            for(int i=0;i<bookDataID.size();i++){
                if(sx == 0){
                    SorX = -1;
                    if(bookDataID.get(i) == wbookids){
                        if(i == 0) SorX = -1;
                        else{
                            SorX = i - 1;
                            wbookids = bookDataID.get(SorX);
                            break;
                        }
                    }
                }else if(sx == 1){
                    SorX = -2;
                    if(bookDataID.get(i) == ebookids){
                        if((i+1) == bookDataID.size()) SorX = -2;
                        else{
                            SorX = i + 1;
                            ebookids = bookDataID.get(SorX);
                            break;
                        }
                    }
                }
            }
            if(SorX == -2) Toast.makeText(getActivity(),"已经没有下一章了！",Toast.LENGTH_SHORT).show();
            else if(SorX == -1) Toast.makeText(getActivity(),"已经没有上一章了！",Toast.LENGTH_SHORT).show();
            else{
                Cursor cs = sql.rawQuery("select chapname,content,chapxl from chapter where chapterid = ?",new String[]{String.valueOf(bookDataID.get(SorX))});
                while (cs.moveToNext()){
                    if(sx == 0) booklook.setText(cs.getString(0)+"\n"+cs.getString(1)+"\n\n"+booklook.getText());
                    else if(sx == 1) booklook.setText(booklook.getText()+"\n\n"+cs.getString(0)+"\n"+cs.getString(1));
                    //区块定位（第一次加载不正常数字为：5/10673, 4/10816，3/22423, 2/33519， 1/44980；【已解决】
                    int suns = 0;
                    if(is == 2){
                        suns = lookbs.getChildAt(0).getMeasuredHeight();
                        or_S = suns;
                        is = 1;
                    }else{
                        suns = lookbs.getChildAt(0).getMeasuredHeight() - or_S;
                        or_S = lookbs.getChildAt(0).getMeasuredHeight();
                    }
                    or_E = lookbs.getChildAt(0).getMeasuredHeight();
                    Txlmap.put(cs.getInt(2),suns);
                    Tidmap.put(cs.getInt(2),bookDataID.get(SorX));
                    getNameANDid(1,0,cef);
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            sql.close();
        }
    }
    //7.监听滚动条确定位置（保存为第一次，滑动后）
    private void getNameANDid(int lj,int S,float W){
        if(lj == 0){
            setSQLrecod(S,W);
        }else{
            for(Map.Entry<Integer,Integer> xlmap:Txlmap.entrySet()){
                if(W - xlmap.getValue() <= 0){
                    setSQLrecod(Tidmap.get(xlmap.getKey()),W);
                    break;
                }else W -= xlmap.getValue();
            }
        }
    }
    /* bookids ：是novel的id
     * 通过is定位
     * 问题：开始是得到了总高度，但随着上下刷新，导致高度在增加，位置变动大。【已解决】
     * 重要一点，因为是不停滑动中不断调用方法计算的话，就会导致资源消耗大，这是不允许的。【已解决】
     */
    //8.保存阅读记录
    private void setSQLrecod(int jlid,float cans){
        int JLS = (int)cans;
        sql = new MySQLOpen(getActivity()).getReadableDatabase();
        try{
            Cursor cs = sql.rawQuery("select * from recod where novelid = ?",new String[]{String.valueOf(bookids)});
            if(cs.moveToFirst()){
                do{
                    ContentValues val = new ContentValues();
                    val.put("chapterid",jlid);
                    val.put("readjl",JLS);
                    sql.update("recod",val,"recodid = ?",new String[]{String.valueOf(cs.getInt(0))});
                }while (cs.moveToNext());
            }else{
                Cursor c = sql.rawQuery("select * from chapter where chapterid = ?",new String[]{String.valueOf(jlid)});
                while (c.moveToNext()){
                    ContentValues val = new ContentValues();
                    val.put("novelid",c.getInt(1));
                    val.put("chapterid",c.getInt(0));
                    val.put("readjl",JLS);
                    sql.insert("recod",null,val);
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(getActivity(),"记录错误！",Toast.LENGTH_SHORT).show();
        }finally {
            sql.close();
        }
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
        void onNOT_WK(int wk);
    }
}
